package com.feel.mall.goodsservice.controller;

import com.feel.mall.common.bean.Goods;
import com.feel.mall.common.bean.RespBean;
import com.feel.mall.common.exception.FeelException;
import com.feel.mall.common.service.GoodsService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: 刘永钦
 * @Description:
 */
@CrossOrigin
@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

//    添加
    @PostMapping
    public RespBean insert(@RequestBody Goods goods) throws FeelException {
        goods.setScore(1F);
        goodsService.insert(goods);
        return RespBean.ok("添加成功");
    }
//    删除
    @DeleteMapping("/{id}")
    public RespBean delete(@PathVariable("id") Integer id) throws FeelException {
        goodsService.delete(id);
        return RespBean.ok("删除成功");
    }
//    修改
    @PutMapping
    public RespBean update(@RequestBody Goods goods) throws FeelException {
        goodsService.update(goods);

        return RespBean.ok("修改成功");
    }
//    查询
    @GetMapping
    public RespBean selectByCondition(Goods condition, Integer pageNum, Integer pageSize) {
        pageNum = pageNum == null || pageNum < 1 ? 1 : pageNum;
        pageSize = pageSize == null || pageSize < 0 ? 5 : pageSize;

        PageInfo<Goods> pageInfo = (PageInfo<Goods>) goodsService.selectByCondition(condition, pageNum, pageSize);

        return RespBean.ok("查询成功", pageInfo);
    }

//    通过id查找
    @GetMapping("/{id}")
    public RespBean selectById(@PathVariable("id") Integer id) {
        Goods goods = goodsService.selectById(id);

        return RespBean.ok("查询成功", goods);
    }

    /**
     * 用户前台获取 商品列表
     */
    @GetMapping("/list")
    public RespBean userGetList(Goods condition, Integer pageNum, Integer pageSize) {
        PageInfo<Goods> pageInfo;

        pageNum = pageNum == null || pageNum < 1 ? 1 : pageNum;
        pageSize = pageSize == null || pageSize < 0 ? 20 : pageSize;

        condition.setStatus(1);
        pageInfo = (PageInfo<Goods>) goodsService.userSelectByCondition(condition, pageNum, pageSize);

        return RespBean.ok("查询成功",pageInfo);
    }
}
